<?php

App::uses('AdminAppController', 'Admin.Controller');
App::uses('AppController', 'Controller');

class StocksController extends AdminAppController {

    var $helpers = array('Form');
    public $components = array(
        'PhpExcel'
    );

    function index() {
        $this->paginate = array(
            'fields' => array(
                'Stock.*', 'Broker.fullname as broker_name'
            ),
            'recursive' => -1,
            'joins' => array(
                array(
                    'table' => 'brokers',
                    'type' => 'left',
                    'alias' => 'Broker',
                    'conditions' => array('Stock.broker = Broker.id')
                )
            ),
            'limit' => 25,
            'order' => array('Stock.id' => 'desc')
        );
        $rows = $this->paginate('Stock');

        // pass the value to our view.ctp
        $this->set('rows', $rows);
    }

    function add() {
        $this->loadModel('Broker');
        $brokers = $this->Broker->find('all');
        $this->set('brokers', $brokers);
        if ($this->request->is(array('post', 'put'))) {
            $this->request->data['date_added'] = date("Y-m-d H:i:s");

            if ($this->Stock->save($this->request->data)) {
                $this->Session->setFlash('Stock has been created.!', 'default', array(), 'good');
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash('Unable to create stock.!', 'default', array(), 'bad');
        }
    }

    function edit($id = null) {
        if (!$id) {
            throw new NotFoundException(__('Invalid post'));
        }
        $post = $this->Stock->findById($id);
        if (!$post) {
            throw new NotFoundException(__('Invalid post'));
        }

        $this->loadModel('Broker');
        $brokers = $this->Broker->find('all');
        $this->set('brokers', $brokers);

        if ($this->request->is(array('post', 'put'))) {
            $this->Stock->id = $id;

            if ($this->Stock->save($this->request->data)) {
                $this->Session->setFlash('Stock has been updated.!', 'default', array(), 'good');
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash('Unable to update stock.!', 'default', array(), 'bad');
        }

        if (!$this->request->data) {
            $this->request->data = $post;
        }
    }

    function delete($id = null) {
        if (!$id) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('get')) {
            throw new MethodNotAllowedException();
        }

        $post = $this->Stock->findById($id);
        if (!$post) {
            throw new NotFoundException(__('Invalid post'));
        }


        if ($this->Stock->delete($id)) {

            $this->Session->setFlash('Delete success!', 'default', array(), 'good');
        } else {
            $this->Session->setFlash('Delete unsuccess!', 'default', array(), 'bad');
        }
        $this->Redirect(array('action' => 'index'));
    }

    function values($stock_id) {
        $this->loadModel('StockValues');

        if (!$stock_id) {
            throw new NotFoundException(__('Invalid stock'));
        }

        $stock = $this->Stock->findById($stock_id);
        if (!$stock) {
            throw new NotFoundException(__('Invalid stock'));
        }

        $this->set('stock', $stock);

        $this->paginate = array(
            'conditions' => array('StockValues.stock' => $stock_id),
            'limit' => 25,
            'order' => array('StockValues.id' => 'desc')
        );
        $rows = $this->paginate('StockValues');

        // pass the value to our view.ctp
        $this->set('rows', $rows);
    }

    function import() {
        $this->loadModel('StockValues');
        $this->loadModel('Opinion');

        $folderToSaveFiles = WWW_ROOT . 'uploads/stocks/';
        if (!$this->request->is('post'))
            return;
        // Not a POST data!


        if (!empty($this->request->data)) {
            //Check if image has been uploaded
            if (!empty($this->request->data['Stock']['stock'])) {
                $file = $this->request->data['Stock']['stock']; //put the data into a var for easy use

                $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
                $arr_ext = array('xls', 'xlsx'); //set allowed extensions
                //only process if the extension is valid
                if (in_array($ext, $arr_ext)) {
                    $newFilename = $file['name'];
                    $new_name = rand(100000000, 999999999) . '_' . $newFilename;
                    $result = move_uploaded_file($file['tmp_name'], $folderToSaveFiles . $new_name);
                    $objPHPExcel = $this->PhpExcel->loadWorksheet($folderToSaveFiles . $new_name);
                    $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                    $i = 0;
                    $text_message[] = '';
                    $imported = 0;
                    foreach ($sheetData as $row) {
                        if ($i && trim($row['A']) != '') {
                            //check exit stock
                            $find_stock = $this->Stock->find('first', array('conditions' => array('name' => trim($row['A']))));
                            if ($find_stock) {
                                $check_value_exit = $this->StockValues->find('first', array('conditions' => array('date BETWEEN "' . $this->request->data['date'] . ' 00:00:00" AND "' . $this->request->data['date'] . ' 23:59:59"', 'stock' => $find_stock['Stock']['id'], 'updated' => $row['S'])));
                                if ($check_value_exit) {
                                    //update value exits
                                    $data = array(
                                        'id' => $check_value_exit['StockValues']['id'],
                                        'phase' => $row['D'],
                                        'vol_bid' => $row['E'],
                                        'bid' => $row['F'],
                                        'vol_ask' => $row['H'],
                                        'ask' => $row['G'],
                                        'last' => $row['I'],
                                        'ep' => $row['J'],
                                        'add_sub' => $row['K'],
                                        'percent' => $row['L'],
                                        'closing' => $row['M'],
                                        'opening' => $row['N'],
                                        'high' => $row['O'],
                                        'low' => $row['P'],
                                        'turnover' => $row['Q'],
                                        'volume' => $row['R'],
                                        'updated' => $row['S'],
                                        'date' => $this->request->data['date']
                                    );
                                } else {
                                    //create value
                                    $data = array(
                                        'stock' => $find_stock['Stock']['id'],
                                        'phase' => $row['D'],
                                        'vol_bid' => $row['E'],
                                        'bid' => $row['F'],
                                        'vol_ask' => $row['H'],
                                        'ask' => $row['G'],
                                        'last' => $row['I'],
                                        'ep' => $row['J'],
                                        'add_sub' => $row['K'],
                                        'percent' => $row['L'],
                                        'closing' => $row['M'],
                                        'opening' => $row['N'],
                                        'high' => $row['O'],
                                        'low' => $row['P'],
                                        'turnover' => $row['Q'],
                                        'volume' => $row['R'],
                                        'updated' => $row['S'],
                                        'date' => $this->request->data['date']
                                    );
                                }
                                $this->StockValues->create();
                                if ($this->StockValues->save($data)) {
                                    $imported++;

                                    //find opinions
                                    $opinions = $this->Opinion->find('all', array('conditions' => array(
                                            'stock' => $find_stock['Stock']['id'],
                                            'and' => array(
                                                'date >=' => $this->request->data['date'] . ' 00:00:00',
                                                'date <=' => $this->request->data['date'] . ' 23:59:59'
                                            )
                                        )
                                    ));

                                    if ($opinions) {
                                        $check_values = $this->StockValues->find('all', array(
                                            'limit' => 2,
                                            'order' => array('date' => 'desc'),
                                            'conditions' => array(
                                                'date <=' => $this->request->data['date'] . ' 23:59:59"',
                                                'stock' => $find_stock['Stock']['id']
                                            )
                                        ));
                                        if ($check_values) {
                                            $opinion_result = 0;
                                            $current_value = $check_values[0]['StockValues']['closing'];
                                            $previous_value = 0;
                                            if (isset($check_values[1])) {
                                                $previous_value = $check_values[1]['StockValues']['closing'];
                                            }
                                            if ($current_value > $previous_value) {
                                                $opinion_result = 0;
                                            } else if ($current_value == $previous_value) {
                                                $opinion_result = 1;
                                            } else {
                                                $opinion_result = 2;
                                            }

                                            foreach ($opinions as $opinion) {
                                                $this->Opinion->id = $opinion['Opinion']['id'];
                                                if ($opinion['Opinion']['opinion'] == $opinion_result) {
                                                    $this->Opinion->save(array('result' => 1));
                                                } else {
                                                    $this->Opinion->save(array('result' => 2));
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    $text_message[] = "Can not import <b>{$row['A']}</b> values";
                                }
                            } else {
                                $this->Stock->create();
                                $stock_data = array(
                                    'broker' => 0,
                                    'fullname' => $row['B'],
                                    'name' => $row['A'],
                                    'market' => $row['C'],
                                    'date_added' => date('Y-m-d H:i:s')
                                );

                                if ($this->Stock->save($stock_data)) {
                                    $data = array(
                                        'stock' => $this->Stock->getLastInsertId(),
                                        'phase' => $row['D'],
                                        'vol_bid' => $row['E'],
                                        'bid' => $row['F'],
                                        'vol_ask' => $row['H'],
                                        'ask' => $row['G'],
                                        'last' => $row['I'],
                                        'ep' => $row['J'],
                                        'add_sub' => $row['K'],
                                        'percent' => $row['L'],
                                        'closing' => $row['M'],
                                        'opening' => $row['N'],
                                        'high' => $row['O'],
                                        'low' => $row['P'],
                                        'turnover' => $row['Q'],
                                        'volume' => $row['R'],
                                        'updated' => $row['S'],
                                        'date' => $this->request->data['date']
                                    );
                                    $this->StockValues->create();
                                    if ($this->StockValues->save($data)) {
                                        $imported++;
                                    } else {
                                        $text_message[] = "Can not import <b>{$row['A']}</b> values";
                                    }
                                } else
                                    $text_message[] = "Can not import <b>{$row['A']}</b> values because stock <b>{$row['A']}</b> not exits on system";
                            }
                        }
                        $i++;
                    }
                    $text_message[0] = "Imported {$imported} stock values";

                    $text_return = '';
                    foreach ($text_message as $v) {
                        $text_return .= $v . '<br>';
                    }

                    $this->Session->setFlash($text_return, 'default', array(), 'good');
                    //prepare the filename for database entry (optional)
                    //$this->data['Image']['image'] = $file['name'];
                    unlink($folderToSaveFiles . $new_name);
                }
            }
        }
    }

}
